<?php

// +----------------------------------------------------------------------
// | ThinkAdmin
// +----------------------------------------------------------------------
// | 版权所有 2014-2018 东莞市云拓互联网络科技有限公司
// +----------------------------------------------------------------------
// | 官方网站:http://www.ytclouds.net
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// +----------------------------------------------------------------------
// |
// +----------------------------------------------------------------------

namespace app\webapi\controller;

use controller\BasicWechat;
use service\DataService;
use service\LogService;
use service\WechatService;
use service\PayService;
use think\Db;
use think\Exception;
use WeChat\Exceptions\InvalidArgumentException;
use WeChat\Exceptions\InvalidResponseException;

/**
 * 微信支付工具
 * Class Tags
 * @package app\wechat\controller
 */
class Wx extends Baseapp
{
    public $payment; //  具体的支付类
    /**
     * 定义当前默认数据表
     * @var string
     */
    public $table = 'SystemConfig';

    private $has_pay_code = 400;        //已经支付了


    /**
     * 微信支付项目
     */
    public function pay()
    {
        $get = $this->request->get();
        //商品用逗号隔开
        $product_ids = isset($get['product_ids']) ? $get['product_ids'] : 0;
        $user_id = $this->user_id;
        if (!$product_ids) {
            $this->error('请选择支付项目！');
        }
        if (!$user_id) {
            $this->error("请重新登录");
        }
        Db::startTrans();
        //生成订单
        $order = $this->create_order($user_id, $product_ids);
        if ($order == false) {
            Db::rollback();
            $this->error("生成订单失败，请稍后重试");
        }
        if ($order['prices'] == 0) {
            //TODO 支付成功
            Db::commit();
            $this->success('支付成功！');
        }
        // 导入具体的支付类文件
        include_once  "public/plugins/payment/weixin/weixin.class.php"; // D:\wamp\www\svn_tpshop\www\plugins\payment\alipay\alipayPayment.class.php
        $code = '\\weixin'; // \alipay
        $this->payment = new $code();
        $code_str = $this->payment->getJSAPI($order);
        Db::commit();
        exit($code_str);

//        $pay_prepayid = $this->pay_prepayid($order);
//
//        if ($pay_prepayid == false) {
//            Db::rollback();
//            $this->error("生成预支付失败，请稍后重试");
//        }
//        if ($pay_prepayid == $this->has_pay_code) {
//            Db::commit();
//            $this->success('订单已经支付了，不要重新付款！');
//        }
    }

    /**
     * 订单生成
     * @param $user_id
     * @param $product_ids
     * @return array|bool
     */
    public function create_order($user_id, $product_ids)
    {
        $product_array = explode(',', $product_ids);
        $where = ['status' => '1', 'is_deleted' => '0', ['id', 'in', $product_array]];
        $fields = 'id,prices';
        $product_list_prices = Db::name('Products')->where($where)->column($fields);
        $needpay = array_sum($product_list_prices);
        Db::startTrans();
        $order_sn = DataService::createSequence(10, 'wechat-pay');
        $order = [
            'order_sn' => 'wechat-pay'.$order_sn,
            'user_id' => $user_id,
            'prices' => $needpay,
            'trade_type' => 'JSAPI'
        ];
        if ($needpay == 0) {
            $order['is_pay'] = 1;
            $order['pay_at'] = time();
        }
        Db::name('Order')->insert($order);
        $r = Db::name('Order')->getLastInsID();
        if (!$r) {
            Db::rollback();
            return false;
        }
        foreach ($product_array as $k => $v) {
            $add_order_goods = [
                'order_id' => $r,
                'product_id' => $v
            ];
            $res = Db::name('OrderGoods')->insert($add_order_goods);
            if (!$res) {
                Db::rollback();
                return false;
            }
        }
        Db::commit();
        $order['id'] = $r;
        return $order;
    }

    /**
     * 微信支付回调
     */
    public function notifyurl(){
        //获取通知的数据
//        $xml = $GLOBALS['HTTP_RAW_POST_DATA'];
        // 导入具体的支付类文件
        include_once  "public/plugins/payment/weixin/weixin.class.php"; // D:\wamp\www\svn_tpshop\www\plugins\payment\alipay\alipayPayment.class.php
        $code = '\\weixin'; // \alipay
        $this->payment = new $code();
        $this->payment->response();
        exit();
    }

    /**
     * 生成预支付订单(弃用)
     * @param $order
     * @return array|bool|int
     */
    public function pay_prepayid($order)
    {
        try {
            $wechat = WechatService::pay();
            // 生成订单号
            $order_no = $order['order_sn'];

            // 该订单号已经支付
            if (PayService::isPay($order_no)) {
                return $this->has_pay_code;
            }
            //获取open_id
            $open_id = WechatService::webOauth(0)['openid'];
//            $open_id = 'o38gpszoJoC9oJYz3UHHf6bEp0Lo';
            //获取IP
            $ip = $_SERVER["REMOTE_ADDR"] ? $_SERVER["REMOTE_ADDR"] : '127.0.0.1';
            //获取notify_url
            //TODO 获取notify_url
            // 4. 组装参数，可以参考官方商户文档
            $options = [
                'body' => '商品支付',
                'out_trade_no' => time() . $order['user_id'],
                'total_fee' => $order['prices'],
                'openid' => $open_id,
                'trade_type' => 'JSAPI',
                'notify_url' => 'http://a.com/text.html',
                'spbill_create_ip' => $ip,
            ];

            $result = $wechat->createOrder($options);
            return $result;

        } catch (InvalidResponseException $e) {
            // 出错啦，处理下吧
            $message = $e->getMessage();
            return $message;
            return false;
        } catch (InvalidArgumentException $e) {
            // 出错啦，处理下吧
            $message = $e->getMessage();
            return $message;
            return false;
        } catch (Exception $e) {
            // 出错啦，处理下吧
            $message = $e->getMessage();
            return $message;
            return false;
        }
    }




}
